from owlready2 import *

# datatype必须在加载本提前使用
class Hex(object):
    def __init__(self, value):
        self.value = value
    
def parser(s):
    return Hex(int(s, 16))

def unparser(x):
    h = hex(x.value)[2:]
    if len(h) %2 != 0: return "0%s" % h
    return h

declare_datatype(Hex, 'http://www.w3.org/2001/XMLSchema#hexBinary', parser, unparser)

def test_parser():
    print('1. test_parser')
    hex = parser('0xFF')
    print('\tparser: ', hex.value)
    print('\tunparser: ', unparser(hex))


def use_hex():
    print('2. use_hex')
    onto = get_ontology("http://www.test.org/t.owl")
    with onto:
        class p(Thing >> Hex): pass
        class C(Thing): pass
        c1 = C()
        c1.p.append(Hex(14))
        print('\tc1.p: ', type(c1.p), c1.p, c1.p[0].value)

def use_predefine():
    print('3. use_predefine')
    onto = get_ontology("http://www.test.org/t.owl")
    define_datatype_in_ontology(Hex, "http://www.w3.org/2001/XMLSchema#hexBinary", onto)
    # 这个例子不能运行, 没有看懂对扩充类型的用法
    # with onto:
    #     class p(Thing >> onto.HexBinary): pass
    #     class C(Thing): pass
    #     c1 = C()
    #     c1.p.append(onto.HexBinary(14))
    #     print('\tc1.p: ', type(c1.p), c1.p, c1.p[0].value)

test_parser()
use_hex()
use_predefine()




